//
//  ReduceViewViewController.swift
//  1604_LimitFree
//
//  Created by 千锋 on 16/9/26.
//  Copyright © 2016年 Mabin. All rights reserved.
//

import UIKit

class ReduceViewViewController: LFBaseViewController {

    //分类的Id
    private var cateId : String?
    
    override func viewDidLoad() {
        super.viewDidLoad()

         self.view.backgroundColor = UIColor.greenColor()
        
        //下拉刷新
        addRedresh()
    }
    
    override func createMyNav() {
        addnavTitle("降价")
        addNavBarbutton("分类", target: self, action: "goToCategaory", isLeft: true)
        addNavBarbutton("设置", target: self, action: "goToSetting", isLeft: false)
    }
    
    //分类
    func goToCategaory()
    {
        let categoryVC = CategoryViewController()
        
        //类型
        categoryVC.type = .Reduce
        
        //设置代理
        categoryVC.delegate = self
        
        self.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(categoryVC, animated: true)
        self.hidesBottomBarWhenPushed = false
    }
    
    func goToSetting()
    {
        let setVc = SettingViewController()
        self.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(setVc, animated: true)
        self.hidesBottomBarWhenPushed = false
    }
    
    
    override func downloaderData() {
        ProgressHUD.showOnView(view)
//        var urlString = kReduceUrl
        var urlString = String(format: kReduceUrl, curPage)
        if cateId != nil
        {
            urlString = urlString.stringByAppendingString("&category_id=\(cateId!)")
        }
        let download = LFDownloader()
        download.delegate = self
        download.downloadWithURLString(urlString)
    }
    
    
//MARK:表格的方法
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 100
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cellId = "reduceCellId"
        var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? ReduceCell
        if cell == nil
        {
            cell = NSBundle.mainBundle().loadNibNamed("ReduceCell", owner: nil, options: nil).last as? ReduceCell
            cell?.selectionStyle = .None
        }
        
        let model = dataArray[indexPath.row] as! LimitModel
        cell?.config(model, atindex: indexPath.row+1)
        return cell!
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        let model = dataArray[indexPath.row] as! LimitModel
        
        let detailVC = DetailViewController()
        detailVC.appId = model.applicationId
        
        self.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(detailVC, animated: true)
        self.hidesBottomBarWhenPushed = false
        
    }
    
}
extension ReduceViewViewController : LFDownloaderDelegate
{
    func downloader(downloader: LFDownloader, didFailWithError error: NSError) {
        
        ProgressHUD.hideAfterFailOnView(view)
    }
    
    func downloader(downloader: LFDownloader, didFinishWithData data: NSData) {
        //如果是下拉刷新,需要清空数组
        if curPage == 1
        {
            dataArray.removeAllObjects()
        }

        //JSON解析
        let result = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)
        if result.isKindOfClass(NSDictionary)
        {
            let dict = result as! Dictionary<String,AnyObject>
            let array = dict["applications"] as! Array<Dictionary<String,AnyObject>>
            for appDict in array
            {
                let model = LimitModel()
                model.setValuesForKeysWithDictionary(appDict)

                dataArray.addObject(model)

            }

            dispatch_async(dispatch_get_main_queue(), {
                
                self.tableView?.reloadData()
                self.tableView?.headerView?.endRefreshing()
                self.tableView?.footerView?.endRefreshing()
                ProgressHUD.hideAfterSuccessOnView(self.view)
            })
        }
    }
}

extension ReduceViewViewController : CategoryViewControllerDelegate
{
    func didClickCateId(cateId: String, cateName: String) {
        var titleStr = "降价-"+cateName
        if cateName == "全部"
        {
            titleStr = "降价"
        }
        addnavTitle(titleStr)
        
        //请求数据
        self.cateId = cateId
        curPage = 1
        downloaderData()
    }
}

